import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Image,
    Text,
    View,
    TouchableOpacity,
    FlatList,
    ActivityIndicator,
    DeviceEventEmitter
} from 'react-native';
type Props = {};
import Toast from 'react-native-easy-toast'
import Confirm from '../../../components/confirm/Confirm'
import {base} from "../../../assets/style";
import { API } from "../../../api";
import { getInterval } from "../../../utils/utils";
import { getLocalTime } from "../../../utils/utils";
import {i18n} from "../../../utils/locales/i18n";

export default class AdvertiseLists extends Component<Props> {
	static navigationOptions = {
		header: null
	}
	constructor() {
		super()
		this.state = {
		    listData: '',
            loading: false,
            modalVisible: false,
            currentId: '',
            currentState: '',
            currentInfo: '',
            isRefresh: false
		}
	}
	componentDidMount(): void {
	    this._initData()
        // DeviceEventEmitter.addListener('refresh_ad', () => {
        //     this._initData()
        // })
    }
    _initData = async () => {
	    this.setState({
            loading: true
        })
        const res = await API._fetch('getAdRecord', {}, 'GET')
        // AdUsername: "dewdew"
        // BankName: "4321234"
        // BankNumber: "6222600260001072444"
        // BuyToken: "hkd"
        // Created: 1546481599
        // FeeFreeze: 0.005
        // FeeRate: 0.005
        // Freeze: 1
        // Id: 44
        // Max: 43
        // Min: 43
        // SellToken: "fcc"
        // State: 1    1 已上架 2 已下架
        // Type: 2
        // Uid: 17
        // Unit: 43
        // Updated: 0

        const type = this.props.type
        const temp = []
        if (res.code === 10000) {
            if (res.data && res.data.length > 0) {
                res.data.forEach(item => {
                    item.key = item.Id + ''
                    // 0 全部 1 已上架 2 已下架 3 已过期
                    item.type = item.State == 1 ? 1 : ( getInterval(Number(item.Created)) < 14 ? 2 : 3 )

                    // 分类
                    if (type === 0) {
                        temp.push(item)
                    } else if (type === item.type) {
                        temp.push(item)
                    }
                })
                // console.log('list data', temp);
            }
            if (temp.length <= 0 && type === 0) {
                temp.push({
                    key: '321',
                    type: 4
                })
            } else if (temp.length <= 0 && type != 0) {
                temp.push({
                    key: '3211',
                    text: i18n.t('i143'),
                    type: 5
                })
            }
        }
        this.setState({
            listData: temp,
            loading: false
        })
    }

    _onRefresh = async () => {
	    await this._initData()
    }
    // 删除广告
    deleteAd = async (id) => {
        this.setState({
            loading: true
        })
        const res = await API._fetch('deleteAd', { id: Number(id) })
        this.setState({
            loading: false
        })
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            setTimeout(async () => {
                DeviceEventEmitter.emit('refresh_ad');
            }, 0)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }
    // 更新广告状态（1上架  2 下架）
    updateAd = async (id, state) => {
        this.setState({
            loading: true
        })
        const res = await API._fetch('updateAd', { id, state })
        // console.log(res);
        this.setState({
            loading: false
        })
        if (res.code === 10000) {
            alert(res.msg || i18n.t('o_success'))
            setTimeout(async () => {
                DeviceEventEmitter.emit('refresh_ad');
            }, 0)
        } else {
            alert(res.msg || i18n.t('o_defeat'))
        }
    }
    handleCancel = () => {
	    this.setState({
            modalVisible: false
        })
    }
    showConfirm = (id, state) => {
	    if (state) {
	        // 修改
            if (state == 1) {
                this.setState({
                    currentInfo: i18n.t('i146')
                })
            } else {
                this.setState({
                    currentInfo: i18n.t('i147')
                })
            }
            this.setState({
                currentState: state,
                modalVisible: true,
                currentId: id
            })
        } else {
	        // 删除
            this.setState({
                currentState: '',
                modalVisible: true,
                currentId: id,
                currentInfo: i18n.t('i148')
            })
        }
    }
    handleConfirm = async () => {
        this.setState({
            modalVisible: false
        })
        if (this.state.currentState) {
            await this.updateAd(this.state.currentId, this.state.currentState)
        } else {
            await this.deleteAd(this.state.currentId)
        }
    }
    render() {
		return (
			<View style={styles.container}>
                {/*模态框*/}
                <Confirm
                    title={i18n.t('info')}
                    negative={i18n.t('cancel')}
                    positive={i18n.t('confirm')}
                    modalVisible={this.state.modalVisible}
                    handleCancelOrder={this.handleCancel}
                    handleConfirmOrder={this.handleConfirm}
                >
                    <View style={[base.flex_1, base.flex_col_center]}>
                        <Text>{i18n.t('i149')}</Text>
                    </View>
                </Confirm>
                {/*toast*/}
                <Toast ref="toast" position='bottom'/>
                { this.state.loading ? (
                    <View style={[base.flex_1, base.flex_col_center, base.bg_white]}>
                        <ActivityIndicator size="large" color="#ff7606" />
                        <View style={{paddingTop: 15}}>
                            <Text style={[base.color_orange]}>{i18n.t('loading')}</Text>
                        </View>
                    </View>
                ) : (
				<FlatList
					data={this.state.listData}
                    onRefresh={() => this._onRefresh()}
                    refreshing={this.state.isRefresh}
					renderItem={
						({item}) => {
							if (item.type === 4) {
                                return (
                                    // 无发布广告
                                    <TouchableOpacity onPress={ () => this.props.toAdverPublish() }>
                                        <View style={[styles.itemContainer, {flexDirection: 'column'}]}>
                                            <View style={{width: '100%', height: '70%', justifyContent: 'center', alignItems: 'center'}}>
                                                <Image source={require('../../../images/adver/adv-none.png')} style={{width: 80, height: 50}}/>
                                            </View>
                                            <View style={{flex: 1, alignItems: 'center'}}>
                                                <Text style={{color: '#fe7809', fontSize: 16}}>{i18n.t('i150')}</Text>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                )
							} else if (item.type === 1) {
								// 上架中
								return (
									<View style={[styles.itemContainer]}>
										<View style={{flex: 1}}>
											<View style={{paddingBottom: 10, borderBottomColor: '#eee', borderBottomWidth: 0.5, alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between'}}>
												<Text style={{fontSize: 18}}>{ item.BuyToken === 'fcc' ? i18n.t('buy') : i18n.t('sell') }FCC</Text>
                                                <View style={[base.flex_col_center, { paddingHorizontal: 5, paddingVertical: 3, borderColor: '#ff7606', borderWidth: 0.3 }]}>
                                                    <Text style={{color: '#ff7604', fontSize: 14}}>{i18n.t('i151')}</Text>
                                                </View>
											</View>
											<View style={{flex: 1, paddingVertical: 10}}>
												<View style={[styles.flex_row_start, {flex: 1}]}>
													<View>
														<Text style={{fontSize: 15}}>{i18n.t('i152')}: </Text>
													</View>
													<View>
														<Text style={{fontSize: 15}}>{ item.Unit } HKD </Text>
													</View>
                                                    <View style={{borderWidth: 1, borderColor: '#68cf6f', backgroundColor: '#68cf6f', paddingVertical: 3, paddingHorizontal: 5, marginLeft: 10}}>
                                                        <Text style={{color: '#fff', fontSize: 12}}>{i18n.t('i122')}</Text>
                                                    </View>
												</View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('i153')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{item.Min} ~ { item.Max } {item.Type === 1 ? 'FCC' : 'HKD'}</Text>
                                                    </View>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('creat_time')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{ getLocalTime(item.Created) }</Text>
                                                    </View>
                                                </View>
											</View>
                                            <View style={[styles.flex_row_end, {height: 30}]}>
                                                <TouchableOpacity onPress={() => this.props.toAdvertiseModify({item})} style={{width: '20%', marginRight: 20}}>
                                                    <View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 0.5, borderColor: '#7f7f7f'}}>
                                                        <Text style={{color: '#7f7f7f'}}>{ i18n.t('i154') }</Text>
                                                    </View>
                                                </TouchableOpacity>
                                                <TouchableOpacity onPress={() => this.showConfirm(item.Id, 2)} style={{width: '20%'}}>
                                                    <View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 0.5, borderColor: '#7f7f7f', backgroundColor: '#7f7f7f'}}>
                                                        <Text style={{color: '#fff'}}>{ i18n.t('i155') }</Text>
                                                    </View>
                                                </TouchableOpacity>
											</View>
										</View>
									</View>
								)
							} else if (item.type === 2) {
								// 已下架
                                return (
                                    <View style={[styles.itemContainer]}>
                                        <View style={{flex: 1}}>
                                            <View style={{paddingBottom: 10, borderBottomColor: '#eee', borderBottomWidth: 0.5, alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between'}}>
                                                <Text style={{fontSize: 18}}>{ item.BuyToken === 'fcc' ? i18n.t('buy') : i18n.t('sell') }FCC</Text>
                                                <View style={[base.flex_col_center, { paddingHorizontal: 5, paddingVertical: 3, borderWidth: 0.3, borderColor: '#b3b3b3' }]}>
                                                    <Text style={{color: '#b3b3b3', fontSize: 14}}>{ i18n.t('i156') }</Text>
                                                </View>
                                            </View>
                                            <View style={{flex: 1, paddingVertical: 10}}>
												<View style={{ position: 'absolute', width: 80, height: 80, top: 5, right: 0 }}>
													<Image style={{width: '100%', height: '100%'}} source={require('../../../images/adver/bg-sold-out.png')}></Image>
												</View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{ i18n.t('i152') }: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{ item.Unit } HKD </Text>
                                                    </View>
                                                    <View style={{borderWidth: 1, borderColor: '#68cf6f', backgroundColor: '#68cf6f', paddingVertical: 3, paddingHorizontal: 5, marginLeft: 10}}>
                                                        <Text style={{color: '#fff', fontSize: 12}}>{i18n.t('i79')}</Text>
                                                    </View>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('i153')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{item.Min} ~ { item.Max } {item.Type === 1 ? 'FCC' : 'HKD'}</Text>
                                                    </View>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('creat_time')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{ getLocalTime(item.Created) }</Text>
                                                    </View>
                                                </View>
                                            </View>
                                            <View style={[styles.flex_row_end, {height: 30}]}>
                                                {/*<TouchableOpacity onPress={() => this.props.toAdvertiseModify({item})} style={{width: '20%', marginRight: 20}}>*/}
                                                    {/*<View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 0.5, borderColor: '#7f7f7f'}}>*/}
                                                        {/*<Text style={{color: '#7f7f7f'}}>{i18n.t('modify')}</Text>*/}
                                                    {/*</View>*/}
                                                {/*</TouchableOpacity>*/}
                                                <TouchableOpacity onPress={() => this.showConfirm(item.Id)} style={{width: '20%', marginRight: 20}}>
                                                    <View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 1, borderColor: '#f78989', backgroundColor: '#f78989'}}>
                                                        <Text style={{color: '#fff'}}>{i18n.t('del')}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                                <TouchableOpacity onPress={() => this.showConfirm(item.Id, 1)} style={{width: '20%'}}>
                                                    <View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 0.5, backgroundColor: '#ff7606', borderColor: '#ff7705'}}>
                                                        <Text style={{color: '#fff'}}>{i18n.t('i157')}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    </View>
                                )
							} else if (item.type === 3) {
                                // 已过期
                                return (
                                    <View style={[styles.itemContainer]}>
                                        <View style={{flex: 1}}>
                                            <View style={{paddingBottom: 10, borderBottomColor: '#eee', borderBottomWidth: 0.5, alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between'}}>
                                                <Text style={{fontSize: 18}}>{ item.BuyToken === 'fcc' ? i18n.t('buy') : i18n.t('sell') }FCC</Text>
                                                <View style={[base.flex_col_center, { paddingHorizontal: 5, paddingVertical: 3, borderWidth: 0.3, borderColor: '#b3b3b3' }]}>
                                                    <Text style={{color: '#b3b3b3', fontSize: 14}}>{i18n.t('i158')}</Text>
                                                </View>
                                            </View>
                                            <View style={{flex: 1, paddingVertical: 10}}>
                                                <View style={{ position: 'absolute', width: 80, height: 80, top: 5, right: 0 }}>
                                                    <Image style={{width: '100%', height: '100%'}} source={require('../../../images/adver/bg-past-due.png')}></Image>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{i18n.t('i152')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={{fontSize: 15}}>{ item.Unit } HKD </Text>
                                                    </View>
                                                    <View style={{borderWidth: 1, borderColor: '#68cf6f', backgroundColor: '#68cf6f', paddingVertical: 3, paddingHorizontal: 5, marginLeft: 10}}>
                                                        <Text style={{color: '#fff', fontSize: 12}}>{i18n.t('i79')}</Text>
                                                    </View>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('i153')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{item.Min} ~ { item.Max } {item.Type === 1 ? 'FCC' : 'HKD'}</Text>
                                                    </View>
                                                </View>
                                                <View style={[styles.flex_row_start, {flex: 1}]}>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{i18n.t('creat_time')}: </Text>
                                                    </View>
                                                    <View>
                                                        <Text style={[styles.itemText]}>{ getLocalTime(item.Created) }</Text>
                                                    </View>
                                                </View>
                                            </View>
                                            <View style={[styles.flex_row_end, {height: 30}]}>
                                                <TouchableOpacity onPress={() => this.showConfirm(item.Id)} style={{width: '20%'}}>
                                                    <View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', borderRadius: 5, borderWidth: 1, borderColor: '#f78989', backgroundColor: '#f78989'}}>
                                                        <Text style={{color: '#fff'}}>{i18n.t('del')}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    </View>
                                )
							} else if (item.type === 5) {
								return (
                                    <View style={{height: 50, width: '100%', backgroundColor: 'transparent', justifyContent: 'center', alignItems: 'center'}}>
                                        <Text style={{color: '#808080'}}>{item.text}</Text>
                                    </View>
								)
							}
						}
					}
				/>
                    )}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		backgroundColor: '#f2f2f2',
		flex: 1,
		width: '100%',
	},
	itemContainer: {
		flex: 1,
		marginHorizontal: 10,
		fontSize: 20,
		height: 170,
		flexDirection: 'row',
		backgroundColor: '#fff',
		borderRadius: 8,		marginTop: 10,
		paddingHorizontal: 20,
		paddingVertical: 10
	},
    flex_row_start: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    flex_row_end: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
	itemText: {
		color: '#808080',
		fontSize: 14
	}
});
